<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- tab标签页 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <!-- 按钮 -->
            <el-button type="primary" size="small" icon="el-icon-plus" class="addRoleBtn" @click="addRoles">新增角色</el-button>
            <!-- 表格 -->
            <el-table
              border
              style="width: 1000px;margin-left:40px"
              :data="rolesLists"
            >
              <el-table-column
                type="index"
                :index="setIndex"
                label="序号"
                width="120"
              />
              <el-table-column
                prop="name"
                label="角色名"
                width="150"
              />
              <el-table-column
                prop="description"
                label="描述"
                width="420"
              />
              <el-table-column
                prop="address"
                label="操作"
                align="center"
              >
                <template #default="{row}">
                  <el-button type="primary" size="mini" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button type="success" size="mini" @click="editRolesInfo(row.id)">修改</el-button>
                  <el-button type="danger" size="mini" @click="deleteRolesById(row.id)">删除</el-button>
                  <!-- <pre>{{ row.id }}</pre> -->
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页设置 -->
            <el-row type="flex" justify="end" class="pagination">
              <el-pagination
                :page-size="3"
                :current-page="pagination.page"
                layout="total, prev, pager, next"
                :total="pagination.total"
                @current-change="changeCurrentPage"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second">
            <!-- 消息提示的文案 -->
            <el-alert
              title="公司信息不可以修改"
              type="info"
              :closable="false"
              show-icon
              class="message"
            />
            <el-row class="companyInfo">
              <el-form label-width="80px">
                <el-form-item label="企业名称">
                  <el-input v-model="companyData.name" style="width:400px" disabled />
                </el-form-item>
                <el-form-item label="公司地址">
                  <el-input v-model="companyData.companyAddress" style="width:400px" disabled />
                </el-form-item>
                <el-form-item label="公司电话">
                  <el-input v-model="companyData.companyPhone" style="width:400px" disabled />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="companyData.mailbox" style="width:400px" disabled />
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="companyData.remarks" style="width:400px" disabled type="textarea" :rows="3" />
                </el-form-item>
              </el-form>
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <!-- 新增/编辑角色对话框 -->
        <el-dialog :title="roleTitle" :visible="dialogFormVisible" @close="onBtnCancel">
          <el-form ref="refForm" :model="newRolesData" :rules="ruleForm">
            <el-form-item label="角色名称" label-width="110px" prop="name">
              <el-input v-model.trim="newRolesData.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色描述" label-width="110px" prop="region">
              <el-input v-model.trim="newRolesData.description" autocomplete="off" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="onBtnCancel">取 消</el-button>
            <el-button type="primary" @click="onSureBtn">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 给角色分配权限对话框 -->
        <el-dialog title="分配权限" :visible="showAssignRolesDialog" @close="btnAssignCancel">
          <el-tree ref="refTrees" :data="permissonList" :props="defaultProps" show-checkbox default-expand-all :check-strictly="true" node-key="id" :default-checked-keys="selectedRoles" />
          <div slot="footer" class="dialog-footer">
            <el-button @click="btnAssignCancel">取 消</el-button>
            <el-button type="primary" @click="btnAssignOk">确 定</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入获取所有角色列表的方法
import { getAllRolesLists, deleteRolesList, getCompanyInfo, getRolesInfo, updateRolesById, addNewRoles } from '@/api/setting.js';
// 导入获取权限列表数据的方法
import { getPermissionList, assignPerm } from '@/api/permission.js';
// 导入转换为树形数据的方法
import { transListToTreeData } from '@/utils/index.js';
// 导入getters
import { mapGetters } from 'vuex';
export default {
  data() {
    return {
      // 分页相关参数
      pagination: {
        total: 0,
        // 当前显示的页码
        page: 1,
        // 每页显示条数
        pagesize: 3,
      },
      rolesLists: [],
      // 存储公司id
      // companyId: 0,
      // 存储公司数据
      companyData: {},
      // 控制对话框的显示和隐藏
      dialogFormVisible: false,
      // 新增角色信息数据
      newRolesData: {
        name: '',
        description: '',
      },
      ruleForm: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
      },
      // 控制tab标签页的默认激活项
      activeName: 'first',
      // 控制分配角色的对话框
      showAssignRolesDialog: false,
      // 权限数据列表
      permissonList: [],
      defaultProps: {
        label: 'name',
      },
      // 存储用于分配权限的角色id
      roleId: null,
      // 默认被勾选的权限信息
      selectedRoles: [],
    };
  },
  computed: {
    ...mapGetters(['companyId']),
    roleTitle() {
      return this.newRolesData.id ? '编辑角色' : '新增角色';
    },
    // 自定义角色列表的索引号
    setIndex() {
      return (this.pagination.page - 1) * this.pagination.pagesize + 1;
    },
  },
  created() {
    this.loadAllRolesLists();
    this.loadCompanyInfo();
  },
  methods: {
    // 加载所有的角色列表信息
    async loadAllRolesLists() {
      const res = await getAllRolesLists({
        page: this.pagination.page,
        pagesize: this.pagination.pagesize,
      });
      // console.log(res);
      this.pagination.total = res.total;
      this.rolesLists = res.rows;
      // this.companyId = res.rows[0].companyId;
      // console.log(this.rolesLists);
      // console.log(this.companyId);
    },
    // 改变页码值
    changeCurrentPage(newPage) {
      this.pagination.page = newPage;
      // 刷新表格数据
      this.loadAllRolesLists();
    },
    async loadCompanyInfo() {
      this.companyData = await getCompanyInfo(this.companyId);
      // console.log(this.companyData);
    },
    // 删除方法
    async deleteRolesById(id) {
      try {
        await this.$confirm('您确定要删除此角色吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        // 一个注意点：await 后面只能接受promise成功的结果，因此如果想要拿到失败的结果，就需要用try 和catch来抓，成功进then，失败进catch，这里用了async/await,如果想要捕获错误，也就是异常，就需要用try 和catch来包裹
        await deleteRolesList(id);
        // 刷新数据列表
        this.loadAllRolesLists();
        this.$message.success('删除成功！');
      } catch (error) {
        // this.$message.error(error);
        console.log(error);
      }
    },
    // 添加新角色
    async addRoles() {
      // 弹出新增角色的对话框
      this.dialogFormVisible = true;
    },
    // 提交编辑/新增角色的信息
    async onSureBtn() {
      // 手动校验表单的信息
      // this.$refs.refForm.validate(async valid => {
      //   if (valid) {
      //     // 校验通过，发起添加角色的请求
      //     await addNewRoles(this.newRolesData);
      //     // 刷新角色列表数据
      //     this.loadAllRolesLists();
      //     this.$message.success('新增角色成功！');
      //     this.dialogFormVisible = false;
      //   }
      // });
      // this.$refs.refForm.resetFields();
      try {
        // 手动校验表单的提交信息
        await this.$refs.refForm.validate();
        if (this.newRolesData.id) {
        // 发送请求，编辑数据的请求
          await updateRolesById(this.newRolesData);
          // 刷新数据
          this.loadAllRolesLists();
          this.$message.success('编辑角色信息成功！');
        } else {
        // 发送请求，处理新增角色业务
          await addNewRoles(this.newRolesData);
          // 刷新数据
          this.loadAllRolesLists();
          this.$message.success('新增角色信息成功！');
        }
        this.dialogFormVisible = false;
      } catch (error) {
        // 这里是为了防止在表单校验未通过的情况下，控制台报错
        console.log(error);
      }
    },
    // 取消编辑角色
    onBtnCancel() {
      // 关闭对话框
      this.dialogFormVisible = false;
      this.newRolesData = {
        name: '',
        description: '',
      };
      // 重置对话框信息
      this.$refs.refForm.resetFields();
    },
    // 编辑角色信息
    async editRolesInfo(id) {
      // 回写数据
      this.newRolesData = await getRolesInfo(id);
      this.dialogFormVisible = true;
    },
    async assignPermission(id) {
      this.permissonList = transListToTreeData(await getPermissionList(), '0');
      this.roleId = id;
      const { permIds } = await getRolesInfo(id);
      this.selectedRoles = permIds;
      // console.log(permIds);
      this.showAssignRolesDialog = true;
    },
    // 提交分配权限信息
    async btnAssignOk() {
      // console.log(this.$refs.refTrees.getCheckedKeys());
      await assignPerm({
        permIds: this.$refs.refTrees.getCheckedKeys(),
        id: this.roleId,
      });
      this.showAssignRolesDialog = false;
      this.$message.success('分配权限成功！');
    },
    btnAssignCancel() {
      this.selectedRoles = [];
      this.showAssignRolesDialog = false;
    },
  },
};
</script>

<style scoped>
.addRoleBtn {
margin: 30px 0 20px 40px;
}
.companyInfo {
  margin-left:100px;
}
.pagination{
  margin: 10px 15px;
}
.message {
  margin-bottom: 20px;
}
</style>
